<?php
namespace api\modules\v1\models\shop;

use api\modules\common\models\User;
use api\modules\v1\models\Common;
use api\modules\v1\models\address\UserAddress;
use api\modules\v1\models\user\UserKyc;
use cms\modules\v1\models\express\ExpressCompany;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\im\Im;
use common\models\pay\Alipay;
use common\models\shop\Goods;
use common\models\Status;
use common\models\user\UserUnusualLog;
use common\models\userFund\UserMoneyLog;
use common\services\logistics\LogisticsApiAliyun;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * Class UserActiveRecord
 * @package api\modules\v1\models
 */
class GoodsOrder extends \common\models\shop\GoodsOrder
{
    /**
     * 进入下单前的订单页面
     * @return array
     */
    public function previewOrder() {
        $trans = Yii::$app->db->beginTransaction();
        try {

            $userInfo = (new \api\modules\v1\models\user\User())->checkUser();
            $goodsId = Yii::$app->request->post('goods_id','');
            $num = Yii::$app->request->post('num',1); // 商品数量

            if (empty($goodsId)) {
                throw new Exception('未知商品信息');
            }

            $goodsInfo = Goods::getOneByWhere(['id'=>$goodsId]);
            if ($goodsInfo['status'] == Status::COMMON_RADIO_NO || $goodsInfo['is_delete'] == Status::COMMON_RADIO_NO) {
                throw new Exception('没找到该商品');
            }
            if ($goodsInfo['check_status'] != Status::COMMON_CHECKING_SUCCESS) {
                throw new Exception('该商品未审核');
            }

            $result = [
                'address' => [],
                'goods' => [],
                'order' => [],
            ];

            //1.默认地址显示
            $addressInfo = ( new UserAddress() ) -> getDefault();
            if ($addressInfo['status'] == 0) {
                $result['address'] = $addressInfo['data'];
            }
//            $deputy_image = json_decode($goodsInfo['deputy_image'],true);
//            $images = [];
//            foreach($deputy_image as &$vv){
//                $images[] = static::getImages($vv);
//            }

            $deputyImage = static::getAllImagesWithType($goodsInfo['deputy_image']);
            $images = [];
            foreach($deputyImage as &$vv){
                if ($vv['type'] == 1) {
                    $images[] = $vv['url'];
                }
            }

            $tmp = [
                'id' => $goodsInfo['id'],
                'name' => $goodsInfo ? $goodsInfo['content'] : '',
                'image' => $images['0'],
                'price' => $goodsInfo['price'],
                'old_price' => $goodsInfo['old_price'],
                'num' => $goodsInfo['num'],
                'sale_nums' => (int)$goodsInfo['sale_nums'],
            ];

            $goodsMoney = bcmul($num,$goodsInfo['price'],2);
            $freight = bcmul($goodsInfo['freight'],1,2);
            $totalMoney = bcadd($goodsMoney,$freight,2);

            $result['goods'] = $tmp;
            $result['order'] = [
                'money' => $goodsMoney,
                'freight' => $freight,
                'total_money' => $totalMoney,
            ];

            $trans->commit();
            return Functions::formatRestAPI(0, '', $result);
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 创建订单
     * @return array
     */
    public function createOrder() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            $userInfo = (new User()) -> checkUser();

            $address = Yii::$app->request->post('address_id',0);
            $mark = Yii::$app->request->post('mark','');
            $goodsId = Yii::$app->request->post('goods_id','');
            $num = Yii::$app->request->post('num','');
            $payWay = Yii::$app->request->post('pay_way',0);


            if (empty($payWay)) {
                throw new Exception('请选择支付方式');
            }
            if (!in_array($payWay,array_keys(Status::PAY_WAY_MAP))) {
                throw new Exception('支付方式不合法');
            }

            if (empty($goodsId)) {
                throw new Exception('未知商品信息');
            }

            if (empty($num) || $num < 0) {
                throw new Exception('请选择购买数量');
            }

            # 零钱封禁
            UserUnusualLog::checkUserUnusual($userInfo['id'],Status::USER_UNUSUAL_TYPE_MONEY);

            $goodsInfo = Goods::getOneByWhere(['id'=>$goodsId]);
            if ($goodsInfo['status'] == Status::COMMON_RADIO_NO || $goodsInfo['is_delete'] == Status::COMMON_RADIO_NO) {
                throw new Exception('没找到该商品');
            }
            if ($goodsInfo['check_status'] != Status::COMMON_CHECKING_SUCCESS) {
                throw new Exception('该商品未审核');
            }

//            if ($goodsInfo['is_sell'] == Status::COMMON_RADIO_NO) {
//                throw new Exception('该商品已出售');
//            }

            if($num > $goodsInfo['num']){
                throw new Exception('商品库存不足');
            }

            $userId = $userInfo['id'];
            if ($userId == $goodsInfo['user_id']) {
                throw new Exception('不能购买自己发布的商品');
            }

            // 订单类型，不支持同城交易

            // 查询当前发布人的身份证信息
            $kyc = UserKyc::getOneByWhere(['user_id' => $goodsInfo['user_id'] ],['id_card']);
            // 查询购买人的身份证信息
            $buykyc = UserKyc::getOneByWhere(['user_id' => $userId ],['id_card']);

            if($kyc['id_card'] == $buykyc['id_card']){
                throw new Exception('不能购买自己发布的商品');
            }

            $orderNumber = $this->_createOrderNumber();
            $order['order_number'] = $orderNumber;
            $order['user_id'] = $userId;

            # 1 地址信息
            $addressInfo = UserAddress::getOneInfoById($address);
            if (empty($address) || empty($addressInfo)) {
                throw new Exception('地址信息不能为空');
            }
            if ($addressInfo['user_id'] != $userInfo['id']) {
                throw new Exception('未知地址信息');
            }
            $order['address_id'] = $address;
            $order['address_detail'] = $addressInfo['province_name'] . $addressInfo['city_name'] . $addressInfo['area_name'] . $addressInfo['detail'];
            $order['link_user'] = $addressInfo['name'];
            $order['link_phone'] = $addressInfo['phone'];

            $order['goods_id'] = $goodsId;
            $order['num'] = $num;
            $order['sell_user'] = $goodsInfo['user_id']?:0;
            $order['goods_type'] = $goodsInfo['type'];
            $order['status'] = Status::USER_GOODS_ORDER_STATUS_WAITING_PAY;
            $order['create_time'] = date("Y-m-d H:i:s");
            $order['pay_time'] = date("Y-m-d H:i:s");
            $order['mark'] = $mark;

            // 商品价格
            $goodsMoney = $goodsInfo['price'] * $num;
            // 运费
            $freight = $goodsInfo['freight'] ?: 0;

            $order['money'] = $goodsMoney;
            $order['freight'] = $freight;
            $order['real_money'] = $goodsMoney + $freight;

            $money = $order['real_money'];
            if($money <= 0){
                throw new Exception('支付金额有误');
            }

            $res = static::insertData($order);
            if ($res === false) {
                throw new Exception('订单提交失败，请稍后再试');
            }

            // 先减掉库存  不增加销量
            //   取消订单之后减掉库存
            //   订单完成以后加入销量
            Goods::updateAllCounters(['num' => -1 * $num],['id' => $goodsId]);

            if ($payWay) {
                //余额支付
                if ($payWay == Status::PAY_WAY_MONEY && $money > 0) {
                    $res = $this->balancePay($userInfo, $orderNumber);
                    if ($res['status'] === false) {
                        throw new Exception($res['message']);
                    }
                }

                // 银行卡支付
                if ($payWay == Status::PAY_WAY_BANK && $money > 0) {
                    throw new Exception('暂未开通该支付方式，敬请期待');
                }

                //支付宝支付
                if ($payWay == Status::PAY_WAY_ALIPAY && $money > 0) {
                    $aliPayModel = new Alipay();

                    $resAlipay = $aliPayModel->payGoods($orderNumber, 'app');

                    if (isset($resAlipay['status']) && $resAlipay['status'] === false) {
                        throw new Exception($resAlipay['message']);
                    }
                    $trans->commit();
                    return Functions::formatRestAPI(0, '创建成功，请尽快支付', $resAlipay);
                }
            }



            $trans->commit();
            return Functions::formatRestAPI(0, '下单成功,请等待发货');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI($e->getCode() ? $e->getCode() : 1, $e->getMessage());
        }
    }

    /**
     * 确认收货
     * @return array
     */
    public function confirmReceive() {
        try {
            $user = (new User())->checkUser();
            $post = Yii::$app->request->post();
            $orderNumber = (String) $post['order_number'];

            if (empty($orderNumber)) {
                throw new Exception('未知信息');
            }
            $orderInfo = static::getOneByWhere(['order_number' => $orderNumber]);
            if(empty($orderInfo) || $orderInfo['user_id'] != $user['id']) {
                throw new Exception('未知订单信息');
            }
            $model = new \common\models\shop\GoodsOrder();



            $res = $model->finished($orderInfo['id']);
            if ($res !== true) {
                throw new Exception($res);
            }

            return Functions::formatRestAPI(0, '订单已完成。');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    /**
     * 订单支付
     * @return array
     */
    public function toPay() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            $userInfo = (new User())->checkUser();
            $payWay = Yii::$app->request->post('pay_way',0);
            $orderNumber = Yii::$app->request->post('order_number','');

            if (!$payWay || !array_key_exists($payWay,Status::PAY_WAY_MAP)) {
                throw new Exception('支付方式有误');
            }

            if (empty($orderNumber)) {
                throw new Exception('订单信息不存在');
            }

            $orderInfo = GoodsOrder::getOneByWhere(['order_number' => $orderNumber]);

            if ($orderInfo['status'] != Status::USER_GOODS_ORDER_STATUS_WAITING_PAY) {
                throw new Exception('订单未处于待支付状态');
            }

            $payMoney = $orderInfo['real_money'];

            //余额支付
            if ($payWay == Status::PAY_WAY_MONEY && $payMoney > 0) {
                $res = $this->balancePay($userInfo, $orderNumber);
                if ($res['status'] === false) {
                    throw new Exception($res['message']);
                }
                $trans->commit();
                return Functions::formatRestAPI(0, '支付成功,请等待发货');
            }


            //支付宝支付
            if ($payWay == Status::PAY_WAY_ALIPAY && $payMoney > 0) {
                $aliPayModel = new Alipay();

                $resAlipay = $aliPayModel->payGoods($orderNumber, 'app');

                if (isset($resAlipay['status']) && $resAlipay['status'] === false) {
                    throw new Exception($resAlipay['message']);
                }
                $trans->commit();
                return Functions::formatRestAPI(0, '请尽快支付', $resAlipay);
            }

        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 取消订单
     * @return array
     */
    public function cancel() {
        try {
            $user = (new User())->checkUser();

            $orderNumber = Yii::$app->request->post('order_number');
            if (empty($orderNumber)) {
                throw new Exception('未知订单信息');
            }

            $orderInfo = static::getOneByWhere(['order_number' => $orderNumber]);
            if (empty($orderInfo) || $orderInfo['user_id'] != $user['id']) {
                throw new Exception('未找到订单信息');
            }

            $res = (new GoodsOrder())->cancelOrder($orderInfo['id'], '用户主动取消订单');
            if ($res !== true) {
                throw new Exception($res['message']);
            }
            return Functions::formatRestAPI(0, '取消成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getStatusMap() {
        $result = [];
        foreach (Status::USER_GOODS_ORDER_STATUS_MAP as $k => $v) {
            $result[] = [
                'id' => (int) $k,
                'name' => $v,
            ];
        }
        return Functions::formatRestAPI(0, '', $result);
    }

    /**
     * 订单列表
     * @param int $page
     * @param int $size
     * @param int $status
     * @return array
     */
    public function getList($page = 1, $size = 50, $status = 0) {
        try {
            $page = (int) $page;
            $size = (int) $size;
            $userInfo = (new User())->checkUser();
            $where['user_id'] = $userInfo['id'];
            $where['is_delete'] = Status::COMMON_RADIO_NO;
            if (!empty($status)) {
                $where['status'] = (int) $status;
            }

            $count = static::getCountByWhere($where);
            $data = static::setPageinationAPI($page, $size, $count);

            $offset = ($page - 1) * $size;
            $list = static::getObjectByWhere($where, ['*'], 'create_time DESC', $offset, $size)
                ->with(['goods','user'])->asArray()->all();

            $result = [];
            $ids = [];
            foreach ($list as $k => $v) {

                $goods = ArrayHelper::getValue($v,'goods',[]);
                $user = ArrayHelper::getValue($v,'user',[]);
                $goodsDetailTmp = [];
                if ($goods) {
                    $deputyImage = static::getAllImagesWithType($goods['deputy_image']);
                    $images = [];
                    foreach($deputyImage as &$vv){
                        if ($vv['type'] == 1) {
                            $images[] = $vv['url'];
                        }
                    }
                    $goodsDetailTmp = [
                        'name' => $goods['content'],
//                        'image' => \common\models\Common::getAllImages($goods['deputy_image'])[0],
                        'image' => $images[0],
                        'price' => floatval($goods['price']),
                        'type' => (int)$goods['type'],
                        'type_name' => Status::GOODS_TYPE_MAP[$goods['type']],
                    ];
                }
                $userInfo = [
                    'id' => $user['id'],
                    'nick_name' => $user['nick_name'],
                    'user_face' => \common\models\Common::getAvatar($user['user_face']) ,
                ];

                $result[] = [
                    'id' => (int) $v['id'],
                    'order_number' => $v['order_number'],
                    'money' => $v['money'],
                    'num' => $v['num'],
                    'link_user' => $v['link_user'],
                    'link_phone' => $v['link_phone'],
                    'address_detail' => $v['address_detail'],
                    'create_time' => $v['create_time'],
                    'pay_time' => $v['pay_time'] ?: '',
                    'status' => $v['status'],
                    'statusName' => Status::USER_GOODS_ORDER_STATUS_MAP[$v['status']],
                    'goods_type' => $v['goods_type'],
                    'typeName' => Status::GOODS_TYPE_MAP[$v['goods_type']],
                    'goods_detail' => $goodsDetailTmp,
                    'user' => $userInfo,
                    'express_number' => $v['express_number']?: '',
                    'express_name' => $v['express_name']?: '',
                    'freight' => $v['freight'] ?: "0",
                ];

                $ids[] = $v['id'];

            }

            if ($ids) {
                # 设为已读
                static::updateData(['is_read' => Status::COMMON_RADIO_YES],['id' => $ids]);
            }

            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 订单详细信息
     * @param int $id
     * @return array
     */
    public function getFullInfo($id = 0) {
        try {
            $user = (new User())->checkUser();

            if (empty($id)) {
                throw new Exception('未知信息');
            }
            $where['id'] = $id;

            $orderInfo = static::getObjectOneByWhere($where)->with(['goods','user'])->asArray()->one();
            if (empty($orderInfo) || $orderInfo['user_id'] != $user['id'] || $orderInfo['is_delete'] == Status::COMMON_IS_DELETE) {
                throw new Exception('未找到订单信息');
            }

            $goodsInfo = ArrayHelper::getValue($orderInfo,'goods',[]);
            $user = ArrayHelper::getValue($orderInfo,'user',[]);

            $detail = [];
            if ($goodsInfo) {
                $deputyImage = static::getAllImagesWithType($goodsInfo['deputy_image']);
                $images = [];
                foreach($deputyImage as &$vv){
                    if ($vv['type'] == 1) {
                        $images[] = $vv['url'];
                    }
                }
                $tmp = [
                    'name' => $goodsInfo['content'],
//                    'image' =>  $this->getAllImages($goodsInfo['deputy_image'])[0],
                    'image' =>  $images[0],
                    'price' => floatval($goodsInfo['price']),
                    'type' => $goodsInfo['type'],
                    'type_name' => Status::GOODS_TYPE_MAP[$goodsInfo['type']],
                ];
                $detail = $tmp;
            }

            $order = [
                'id' => (int) $orderInfo['id'],
                'order_number' => $orderInfo['order_number']?: '',
                'money' => $orderInfo['money']?: '',
                'mark' => $orderInfo['mark']?: '',
                'create_time' => $orderInfo['create_time']?: '',
                'pay_time' => $orderInfo['pay_time'] ?: '',
                'deliver_goods_time' => $orderInfo['deliver_goods_time'] ?: '',
                'finish_time' => $orderInfo['finish_time'] ?: '',
                'express_number' => $orderInfo['express_number']?: '',
                'express_name' => $orderInfo['express_name']?: '',
                'status' => $orderInfo['status'],
                'statusName' => Status::USER_GOODS_ORDER_STATUS_MAP[$orderInfo['status']],
                'is_extend_confirm' => $orderInfo['is_extend_confirm'] == Status::COMMON_RADIO_YES,
                'freight' => $orderInfo['freight'] ?: "0",
                'num' => $orderInfo['num'] ?: "0",
                'real_money' => $orderInfo['real_money'] ?: "0",
            ];
            $address = [
                'link_user' => $orderInfo['link_user'],
                'link_phone' => $orderInfo['link_phone'],
                'address' => $orderInfo['address_detail'],
            ];
            $userInfo = [
                'id' => $user['id'],
                'nick_name' => $user['nick_name'],
                'user_face' => \common\models\Common::getImages($user['user_face']),
            ];
            $data['orderInfo'] = $order;
            $data['goodsInfo'] = $detail;
            $data['user'] = $userInfo;
            $data['address'] = $address;
            $data['is_sell'] = (bool) $order['sell_user'] == $user['id']; //是否是自己售卖的产品

            // 查看退款数据
            $returnWhere['order_number'] = $orderInfo['order_number'];
            $returnOrderInfo = GoodsOrderReturn::getOneByWhere($returnWhere);
            $refundInfo = null;
            if ($returnOrderInfo) {
                $refundInfo['reason'] = $returnOrderInfo['reason'];
                $refundInfo['status'] = $returnOrderInfo['status'];
                $refundInfo['status_name'] = Status::USER_GOODS_ORDER_STATUS_MAP[$returnOrderInfo['status']] ?? '';
                $refundInfo['reject'] = $returnOrderInfo['reject'];
            }
            $data['refund'] = $refundInfo;
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /* ====================== 商户相关 ========================= */
    /**
     * 卖出的
     * @param int $page
     * @param int $size
     * @param int $status
     * @return array
     */
    public function getBusinessList($page = 1, $size = 50, $status = 0)
    {
        try{
            $page = (int)$page;
            $size = (int)$size;
            $userInfo = (new User())->checkUser();

            if (!empty($status)) {
                $where['status'] = (int) $status;
            }

            $where['sell_user'] = $userInfo['id'];

            $count = static::getCountByWhere($where);
            $data = static::setPageinationAPI($page, $size, $count);

            $offset = ($page - 1) * $size;
            $list = static::getObjectByWhere($where, ['*'], 'create_time DESC', $offset, $size)
                ->with(['goods','user'])->asArray()->all();
            $result = [];
            $ids = [];
            foreach ($list as $k => $v) {
                $goods = ArrayHelper::getValue($v,'goods',[]);
                $user = ArrayHelper::getValue($v,'user',[]);
                $goodsDetailTmp = [];


                if ($goods) {
//                    $deputy_image = json_decode($goods['deputy_image'],true);
//                    foreach($deputy_image as &$vv){
//                        $images[] = $this->getImages($vv);
//                    }

                    $deputyImage = static::getAllImagesWithType($goods['deputy_image']);
                    $images = [];
                    foreach($deputyImage as &$vv){
                        if ($vv['type'] == 1) {
                            $images[] = $vv['url'];
                        }
                    }
                    $goodsDetailTmp = [
                        'name' => $goods['content'],
                        'img' => $images[0] ?? '',
                        'price' => floatval($goods['price']),
                        'type' => (int)$goods['type'],
                        'num' => (int)$goods['num'],
                        'sale_nums' => (int)$goods['sale_nums'],
                        'type_name' => Status::GOODS_TYPE_MAP[$goods['type']],
                    ];
                }
                $userInfo = [
                    'id' => $user['id'],
                    'nick_name' => $user['nick_name'],
                    'user_face' => static::getAvatar($user['user_face']),
                ];

                $result[] = [
                    'id' => (int) $v['id'],
                    'order_number' => $v['order_number'],
                    'money' => $v['money'],
                    'num' => $v['num'],
                    'link_user' => $v['link_user'],
                    'link_phone' => $v['link_phone'],
                    'address_detail' => $v['address_detail'],
                    'create_time' => $v['create_time'],
                    'pay_time' => $v['pay_time'] ?: '',
                    'status' => $v['status'],
                    'statusName' => Status::USER_GOODS_ORDER_STATUS_MAP[$v['status']],
                    'goods_type' => $v['goods_type'],
                    'typeName' => Status::GOODS_TYPE_MAP[$v['goods_type']],
                    'goods_detail' => $goodsDetailTmp,
                    'user' => $userInfo,
                    'express_number' => $v['express_number']?: '',
                    'express_name' => $v['express_name']?: '',
                    'freight' => $v['freight'] ?: "0",
                ];
                $ids[] = $v['id'];
            }

            if ($ids) {
                # 设为已读
                static::updateData(['business_is_read' => Status::COMMON_RADIO_YES],['id' => $ids]);
            }

            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        }catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 订单详细信息
     * @param int $id
     * @return array
     */
    public function getBusinessInfo($id = 0) {
        try {
            $user = (new User())->checkUser();

            if (empty($id)) {
                throw new Exception('未知信息');
            }
            $where['id'] = $id;

            $orderInfo = static::getObjectOneByWhere($where)->with(['goods','user'])->asArray()->one();
            if (empty($orderInfo) || $orderInfo['sell_user'] != $user['id']) {
                throw new Exception('未找到订单信息');
            }

            $goodsInfo = ArrayHelper::getValue($orderInfo,'goods',[]);
            $user = ArrayHelper::getValue($orderInfo,'user',[]);

            $detail = [];
            if ($goodsInfo) {
                $deputyImage = static::getAllImagesWithType($goodsInfo['deputy_image']);
                $images = [];
                foreach($deputyImage as &$vv){
                    if ($vv['type'] == 1) {
                        $images[] = $vv['url'];
                    }
                }
                $tmp = [
                    'name' => $goodsInfo['content'],
//                    'image' => $this->getAllImages($goodsInfo['deputy_image'])[0],
                    'image' => $images[0],
                    'price' => floatval($goodsInfo['price']),
                    'type' => $goodsInfo['type'],
                    'type_name' => Status::GOODS_TYPE_MAP[$goodsInfo['type']],
                ];
                $detail = $tmp;
            }

            $order = [
                'id' => (int) $orderInfo['id'],
                'order_number' => $orderInfo['order_number'],
                'money' => $orderInfo['money'],
                'num' => $orderInfo['num'],
                'mark' => $orderInfo['mark'],
                'create_time' => $orderInfo['create_time'],
                'pay_time' => $orderInfo['pay_time'] ?: '',
                'deliver_goods_time' => $orderInfo['deliver_goods_time'] ?: '',
                'finish_time' => $orderInfo['finish_time'] ?: '',
                'express_number' => $orderInfo['express_number'],
                'express_name' => $orderInfo['express_name'],
                'status' => $orderInfo['status'],
                'statusName' => Status::USER_GOODS_ORDER_STATUS_MAP[$orderInfo['status']],
                'freight' => $orderInfo['freight'] ?: "0",
                'real_money' => $orderInfo['real_money'] ?: "0",
            ];
            $address = [
                'link_user' => $orderInfo['link_user'],
                'link_phone' => $orderInfo['link_phone'],
                'address' => $orderInfo['address_detail'],
            ];
            $userInfo = [
                'id' => $user['id'],
                'nick_name' => $user['nick_name'],
                'user_face' => Common::getImages($user['user_face']),
            ];
            $data['orderInfo'] = $order;
            $data['goodsInfo'] = $detail;
            $data['user'] = $userInfo;
            $data['address'] = $address;

            // 查看退款数据
            $returnWhere['order_number'] = $orderInfo['order_number'];
            $returnOrderInfo = GoodsOrderReturn::getOneByWhere($returnWhere);
            $refundInfo = null;
            if ($returnOrderInfo) {
                $refundInfo['reason'] = $returnOrderInfo['reason'];
                $refundInfo['status'] = $returnOrderInfo['status'];
                $refundInfo['status_name'] = Status::USER_GOODS_ORDER_STATUS_MAP[$returnOrderInfo['status']] ?? '';
                $refundInfo['reject'] = $returnOrderInfo['reject'];
            }
            $data['refund'] = $refundInfo;

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 快递列表
     * @return array
     */
    public function getExpressList() {
        $list = ExpressCompany::getByWhere([]);

        if ($list == false) {
            throw new Exception('系统错误');
        }
        return Functions::formatRestAPI(0, '',$list);

    }

    /**
     * 订单发货
     * @return array
     */
    public function deliver() {
        try {
            $userInfo =  Yii::$app->getUser()->getIdentity()->toArray();

            $orderId = Yii::$app->request->post('order_id',0);
            $expressId = Yii::$app->request->post('express_id',0);
            $expressNo = Yii::$app->request->post('express_no','');

            $orderInfo = static::getOneInfoById($orderId);
            if(empty($orderInfo) || $orderInfo['status'] != Status::USER_GOODS_ORDER_STATUS_WAITING_SEND) {
                throw new Exception('未知订单信息');
            }
            if ($orderInfo['sell_user'] != $userInfo['id']) {
                throw new Exception('订单信息不匹配');
            }
            // 订单类型，不支持同城交易
            // if(empty($expressNo) || empty($expressId)){
            //     throw new Exception('请填写物流单号及选择快递公司,无快递发货功能升级中...暂不开放此功能');
            // }

            $update['status'] = Status::USER_GOODS_ORDER_STATUS_WAITING_RECEIVE;
            $update['deliver_goods_time'] = date("Y-m-d H:i:s");
            $update['express_id'] = 0;
            $update['express_number'] = '';
            $update['express_name'] = '无快递';
            if ($expressId) {
                $expressMap = ExpressCompany::getListMapByCache();
                $expressInfo = $expressMap[$expressId];
                $update['express_id'] = $expressId;
                $update['express_name'] = $expressInfo['express_name'];
                $update['express_number'] = $expressNo;
            }

            $res = static::updateData($update, ['id' => $orderId]);

            if ($res === false) {
                throw new Exception('系统错误，请联系开发小哥哥');
            }

            $goodsInfo = Goods::getOneByWhere(['id' => $orderInfo['goods_id']]);

            // 发送IM消息 发给订单用户
            $userMessage = [];
            $userMessage['message_type'] = (int) Status::MESSAGE_TYPE_USER_SHOP_MESSAGE;
            $userMessage['type'] = (int) Status::MESSAGE_TYPE_USER_SHOP_MESSAGE;
            $userMessage['title'] = "订单发货通知";
            $userMessage['desc'] = "商品发货成功~";
            if ($expressId) {
                $userMessage['express_number'] = $expressNo;
            }
            $userMessage['express_name'] = $update['express_name'];
            $userMessage['goods_info'] = $goodsInfo['content'] .' * '. $orderInfo['num'];
            $userMessage['address'] = $orderInfo['address_detail'];
            $userMessage['order_number'] = $orderInfo['order_number'];
            $userMessage['order_id'] = $orderInfo['id'];
            $userMessage['time'] = date('Y-m-d H:i:s');
            $userMessage['is_sell'] = false; // 是否是自己的商品

            $config = static::getCommonByKey('shop_user_id');
            // 发给订单用户
            $userInfo = User::getOneByWhere(['id' => $orderInfo['user_id']]);
            (new Im()) -> sendUserMessage($userInfo['tx_code'], $userMessage, $config);

            // 发给商品用户
            $userInfo = User::getOneByWhere(['id' => $goodsInfo['user_id']]);
            if ($userInfo) {
                $userMessage['is_sell'] = true; // 是否是自己的商品
                (new Im()) -> sendUserMessage($userInfo['tx_code'], $userMessage, $config);
            }

            return Functions::formatRestAPI(0, '发货成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 同意或驳回申请
     * @param int $id
     * @return array
     */
    public function saveReturnInfo() {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $userInfo = (new User())->checkUser();

            $status = Yii::$app->request->post('status','0');
            $orderId = Yii::$app->request->post('order_id','0');
            $reject = Yii::$app->request->post('reject');
            if(!$status){
                throw new Exception('未知状态');
            }
            if (empty($orderId)) {
                throw new Exception('未知信息');
            }
            $returnInfo = GoodsOrderReturn::getOneByWhere(['order_id'=>$orderId]);
            if(empty($returnInfo) || $returnInfo['status'] != Status::USER_GOODS_ORDER_SHENQING) {
                throw new Exception('退款信息不存在');
            }
            $goodsInfo = Goods::getOneInfoById($returnInfo['goods_id']);
            if (empty($goodsInfo) || $goodsInfo['user_id'] != $userInfo['id']) {
                throw new Exception('退款信息不匹配');
            }

            if (!in_array($status,[Status::USER_GOODS_ORDER_RETURNOK,Status::USER_GOODS_ORDER_RETURNNO])) {
                throw new Exception('退款参数不合法');
            }
            if ($status == Status::USER_GOODS_ORDER_RETURNNO){//驳回退款
                //更新状态
                if(empty($reject)){
                    throw new Exception('填写驳回理由');
                }
            }

            // 执行退款
            $this->confirmReturnOrder($orderId,$status,$reject ? $reject : "商户同意退款");

//            $return_money = $returnInfo['return_money'];
//
//            $orderInfo = static::getOneByWhere(['id' => $orderId]);
//            $orderUserInfo = User::getOneByWhere(['id' => $orderInfo['user_id']]);
//
//            // 发送IM消息 发给订单用户
//            $userMessage = [];
//            $userMessage['message_type'] = (int) Status::MESSAGE_TYPE_USER_SHOP_MESSAGE;
//            $userMessage['type'] = (int) Status::MESSAGE_TYPE_USER_SHOP_MESSAGE;
//            $config = static::getCommonByKey('shop_user_id');
//
//            if($status == Status::USER_GOODS_ORDER_RETURNOK){ //同意退款
//                //更新退款表
//                $returnData['reject_time'] = date('Y-m-d H:i:s');
//                $returnData['status'] = Status::USER_GOODS_ORDER_RETURNOK;
//                $orderReturn = GoodsOrderReturn::updateData($returnData,['order_id'=>$orderId]);
//                if($orderReturn == false){
//                    throw new Exception('退款状态更新失败');
//                }
//                //更新订单表
//                $OrderData['finished_time'] = date('Y-m-d H:i:s');
//                $OrderData['status'] = Status::USER_GOODS_ORDER_RETURNOK;
//                $order = static::updateData($OrderData,['id'=>$orderId]);
//                if($order == false){
//                    throw new Exception('订单状态更新失败');
//                }
//
//
//                if ($orderInfo['pay_way'] == Status::PAY_WAY_ALIPAY) {
//                    $alipayRes = (new Alipay())->refundGoods($orderInfo['order_number']);
//                    if (!$alipayRes) {
//                        throw new Exception('支付宝退款失败');
//                    }
//                } else {
//                    //商品退款
//                    UserMoneyLog::record(
//                        $returnInfo['user_id'],
//                        Status::PROP_TYPE_MONEY,
//                        Status::MONEY_LOG_TYPE_BUT_GOODS_RETURN,
//                        $return_money,
//                        Status::MONEY_LOG_TYPE_MAP[Status::MONEY_LOG_TYPE_BUT_GOODS_RETURN] ?? '',
//                        '商品退款'
//                    );
//                }
//
//
//                if(!empty($orderInfo['sell_user'])){
//                    // 给卖家减少橱窗余额
//                    UserMoneyLog::record(
//                        $orderInfo['sell_user'],
//                        Status::PROP_TYPE_SHOP_MONEY,
//                        Status::SHOP_MONEY_LOG_TYPE_GOODS_REFUND,
//                        -1 * abs($orderInfo['real_money']),
//                        Status::SHOP_MONEY_LOG_TYPE_MAP[Status::SHOP_MONEY_LOG_TYPE_GOODS_REFUND] ?? '',
//                        '商家同意退款'
//                    );
//                }
//
//                $msg = '退款成功';
//
//                // 发送IM消息 发给订单用户
//                $userMessage['title'] = "订单退款成功";
//                $userMessage['desc'] = $return_money;
//                $userMessage['goods_info'] = $goodsInfo['content'] .' * '. $orderInfo['num'];
//                $userMessage['address'] = $orderInfo['address_detail'];
//                $userMessage['order_number'] = $orderInfo['order_number'];
//                $userMessage['order_id'] = $orderInfo['id'];
//                $userMessage['time'] = date('Y-m-d H:i:s');
//                $userMessage['is_sell'] = false; // 是否是自己的商品
//                // 发给订单用户
//                (new Im()) -> sendUserMessage($orderUserInfo['tx_code'], $userMessage, $config);
//
//                // 发给商品用户
//                if ($userInfo) {
//                    $userMessage['is_sell'] = true; // 是否是自己的商品
//                    (new Im()) -> sendUserMessage($userInfo['tx_code'], $userMessage, $config);
//                }
//
//            }elseif ($status == Status::USER_GOODS_ORDER_RETURNNO){//驳回退款
//                //更新状态
//                if(empty($reject)){
//                    throw new Exception('填写驳回理由');
//                }
//                $returnData['reject'] = $reject;
//                $returnData['reject_time'] = date('Y-m-d H:i:s');
//                $returnData['status'] = Status::USER_GOODS_ORDER_RETURNNO;
//                //更新退款表
//                $orderReturn = GoodsOrderReturn::updateData($returnData,['order_id'=>$orderId]);
//                if(!$orderReturn){
//                    throw new Exception('退款状态更新失败');
//                }
//                //更新订单表
//                $order = GoodsOrder::updateData(['status'=>Status::USER_GOODS_ORDER_RETURNNO],['id'=>$orderId]);
//                if(!$order){
//                    throw new Exception('订单状态更新失败');
//                }
//                $msg = '驳回成功';
//
//                // 发送IM消息 发给订单用户
//                $userMessage['title'] = "订单退款失败";
//                $userMessage['desc'] = $reject;
//                $userMessage['goods_info'] = $goodsInfo['content'] .' * '. $orderInfo['num'];
//                $userMessage['address'] = $orderInfo['address_detail'];
//                $userMessage['order_number'] = $orderInfo['order_number'];
//                $userMessage['order_id'] = $orderInfo['id'];
//                $userMessage['time'] = date('Y-m-d H:i:s');
//                $userMessage['is_sell'] = false; // 是否是自己的商品
//                // 发给订单用户
//                (new Im()) -> sendUserMessage($orderUserInfo['tx_code'], $userMessage, $config);
//
//                // 发给商品用户
//                if ($userInfo) {
//                    $userMessage['is_sell'] = true; // 是否是自己的商品
//                    (new Im()) -> sendUserMessage($userInfo['tx_code'], $userMessage, $config);
//                }
//
//            }else{
//                throw new Exception('参数异常');
//            }
            $trans->commit();
            return Functions::formatRestAPI(0, "操作成功");
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 商家取消订单
     * @return array
     */
    public function shopCancelOrder() {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $userInfo = (new User())->checkUser();

            $orderNumber = Yii::$app->request->post('order_number','');
            $reason = Yii::$app->request->post('reason','');
            if(!$reason){
                throw new Exception('请填写取消原因');
            }
            if (empty($orderNumber)) {
                throw new Exception('未知信息');
            }
            $orderInfo = static::getOneByWhere(['order_number' => $orderNumber]);
            if(empty($orderInfo)) {
                throw new Exception('订单信息不存在');
            }
            if ($orderInfo['sell_user'] != $userInfo['id']) {
                throw new Exception('订单信息不匹配');
            }

            if (!in_array($orderInfo['status'],[
                Status::USER_GOODS_ORDER_STATUS_WAITING_PAY,
                Status::USER_GOODS_ORDER_STATUS_WAITING_SEND,
            ])) {
                throw new Exception('该订单无法取消');
            }

            $mark = '商家取消订单，原因：' . $reason;
            $this->shopOrAdminCancelOrder($orderNumber,$mark);
            $trans->commit();
            return Functions::formatRestAPI(0, '取消成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    /**
     * 查看物流
     * @return array
     */
    public function showLogistics() {
        try {
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $orderNumber = Yii::$app->request->get('order_number','');
            if (empty($orderNumber)) {
                throw new Exception('查询的单号有误');
            }
            $where['order_number'] = $orderNumber;
            $orderInfo = static::getObjectOneByWhere($where)->with(['goods','user'])->asArray()->one();
            if (empty($orderInfo)) {
                throw new Exception('未找到订单信息');
            }

            if (empty($orderInfo['express_number'])) {
                throw new Exception('该订单没有物流单号，不支持查看');
            }

            $resultData = [];
//            $result = LogisticsApiAliyun::queryLogistics('9850343651538');
            $result = LogisticsApiAliyun::queryLogistics($orderInfo['express_number']);
            if ($result['status'] != 0) {
                throw new Exception($result['msg']);
            }
            $resultData = $result['result'];
            $resultData['address_detail'] = $orderInfo['address_detail'];
            $resultData['order_number'] = $orderNumber;
            return Functions::formatRestAPI(0, '', $resultData);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 延迟收货，每个订单只能延迟一次
     * @return array
     */
    public function extendConfirm() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            $userInfo = (new User())->checkUser();

            $orderNumber = Yii::$app->request->post('order_number','');

            if (empty($orderNumber)) {
                throw new Exception('未知订单信息');
            }
            $orderInfo = static::getOneByWhere(['order_number' => $orderNumber]);
            if(empty($orderInfo)) {
                throw new Exception('订单信息不存在');
            }
            if ($orderInfo['user_id'] != $userInfo['id']) {
                throw new Exception('订单信息不匹配');
            }

            if (!in_array($orderInfo['status'],[
                Status::USER_GOODS_ORDER_STATUS_WAITING_RECEIVE,
            ])) {
                throw new Exception('该订单无法延迟收货');
            }

            $this->extendFinished($orderNumber);
            $trans->commit();
            return Functions::formatRestAPI(0, '延迟收货成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


}
